﻿/*
 * Created by SharpDevelop.
 * User: kwu
 * Date: 2007-4-8
 * Time: 15:40
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Windows.Forms;

using XihSolutions.DotMSN;
using XihSolutions.DotMSN.Core;

namespace msnkiller
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		private XihSolutions.DotMSN.Messenger fMsgClient = new Messenger();
		//private System.Collections.Hashtable _cons = new Hashtable();
		private System.Collections.ArrayList _cons = new ArrayList();
		private System.Collections.Hashtable _ConversationPool = new Hashtable();
		private Judge fJudge = new Judge();
		
		[STAThread]
		public static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm());
		}
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			fMsgClient.Credentials.ClientID = "msmsgs@msnmsgr.com";
			fMsgClient.Credentials.ClientCode = "Q1P7W2E4J9R8U3S5";			
			fMsgClient.Credentials.Account = "msnkilltest@hotmail.com";
			fMsgClient.Credentials.Password = "fatboyslim";
		  
      fMsgClient.Nameserver.ServerErrorReceived += new ErrorReceivedEventHandler(On_ServerError);
			
			fMsgClient.Nameserver.SignedIn += new EventHandler(On_SignedIn);
			fMsgClient.Nameserver.ReverseAdded += new ContactChangedEventHandler(On_Invited);
			fMsgClient.ConversationCreated += new ConversationCreatedEventHandler(On_GetConversation);
			
			fJudge.SaidBack += new Judge.SaybackDelegate(On_MsgNeedSend);
			
			// TODO: 命令别称
			// TODO: 话前面加昵称而不是邮件地址
      // TODO: 对话记录，出错记录
			// TODO: 配置文件方式存放帐号密码，可配置显示图片，可配置每个人个人设置
			// TODO: 8，发消息报800错误，之后一直差一句的问题
			// TODO: 4，web方式一段时间后服务端收不到消息
			// TODO: 第一次进入显示加入对话人数
      // TODO: iloveim web端收不到消息,退出时导致出错
		}
		
		private void On_Invited(object sender, ContactEventArgs e)
		{
		  fMsgClient.Nameserver.AddContactToList(e.Contact, MSNLists.AllowedList);
		  Invoke(new ShowMsgDelegate(ShowMsg), new object[]{e.Contact.Name, "加入了"});
		}
		
		private void On_ServerError(object sender, MSNErrorEventArgs e)
		{
		  //MessageBox.Show(e.MSNError.ToString(), "Server error received");
			//SetStatus("Server error received");
		}
		
		
		private void On_GetConversation(object sender, ConversationCreatedEventArgs e)
		{
  		e.Conversation.Switchboard.TextMessageReceived += new TextMessageReceivedEventHandler(On_GetMsg);
		  if (e.Conversation.Switchboard.Contacts.Count == 1)
		  {
		    foreach(DictionaryEntry de in e.Conversation.Switchboard.Contacts)
		    {
		      _ConversationPool.Add(de.Key, e.Conversation);
		    }
		  }
		}
		
		private delegate void ShowMsgDelegate(string name, string msg);
		private void ShowMsg(string name, string msg)
		{
		  label1.Text = name + "：" + msg;
		}
		
		private void On_MsgNeedSend(string msg, ArrayList accounts)
		{
		  SendMsg(msg, accounts);
		}
		
		private void On_GetMsg(object sender, TextMessageEventArgs e)
		{
		  //SendMsg(CreateTextMsg(e.Sender, e.Message));
		  Invoke(new ShowMsgDelegate(ShowMsg), new object[]{e.Sender.Name, e.Message.Text});
		  fJudge.SbSay(e.Sender.Mail, e.Message.Text);
		}
		
		private void SendMsg(string msg, ArrayList accounts)
		{
		  TextMessage textMsg = new TextMessage(msg);
		  foreach (string mail in accounts)
		  {
		    //Conversation conversation = fMsgClient.CreateConversation();
		    Conversation conversation = GetConversation(mail);
		    if (conversation.Switchboard.Contacts.Count == 0)
		    {
  		    conversation.Switchboard.ContactJoined += delegate(object sender, ContactEventArgs e) { 
  		      (sender as SBMessageHandler).SendTextMessage(textMsg);};
  		    conversation.Invite(mail);
		    }
		    else
		    {
          if (conversation.SwitchboardProcessor.Connected == false)
          {
            conversation.Messenger.Nameserver.RequestSwitchboard(conversation.Switchboard, this);
          }
		      conversation.Switchboard.SendTextMessage(textMsg);
		    }
		  }
		}
		
		private Conversation GetConversation(string mail)
		{
		  Conversation result = _ConversationPool[mail] as Conversation;
		  if (result == null || result.Switchboard.Contacts.Count==0)
		  {
		    result = fMsgClient.CreateConversation();
		    _ConversationPool[mail] = result;
		  }
		  return result;
		}
		
		private void On_SignedIn(object sender, EventArgs e)
		{
			fMsgClient.Owner.DisplayImage.LoadFile("chartImg.jpg");
			fMsgClient.Nameserver.Owner.Status = PresenceStatus.Online;
		}
			
		void LoginBtnClick(object sender, EventArgs e)
		{
			if (fMsgClient.Connected)
			{
				fMsgClient.Disconnect();
			}
		
			fMsgClient.Connect();			
		}
	}
}
